package cn.junki.jpaencryptdemo.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * 自定义转换器：入库加密，出库解密
 *
 * @author Junki
 * @date 2023-09-08 11:07:22
 */
@Converter // Converter属性autoApply，如果设置为true，未指定的字段也会被加密
public class EncryptConverter implements AttributeConverter<String, String> {

    private final String AES_KEY = "hello-junki-blog";

    /**
     * 加密
     */
    @Override
    public String convertToDatabaseColumn(String text) {
        // 空白内容不加密
        if (StrUtil.isNotBlank(text)) {
            text = SecureUtil.aes(AES_KEY.getBytes()).encryptHex(text);
        } else {
            text = null;
        }
        return text;
    }

    /**
     * 解密
     */
    @Override
    public String convertToEntityAttribute(String ciphertext) {
        if (StrUtil.isNotBlank(ciphertext)) {
            ciphertext = SecureUtil.aes(AES_KEY.getBytes()).decryptStr(ciphertext);
        } else {
            ciphertext = null;
        }
        return ciphertext;
    }

}